// ActionScript file

private function CheckTimeDifference(newTime:String):Number {
	var TimeOpened:Date = new Date(newTime) as Date;
	var Now:Date = new Date();
	var TO:Object = new Object();
	
	TO = TimeUtil.getDifference(TimeOpened, Now);
	return (TO.minutes * 60) + TO.seconds as Number; 
	
}
			
private function DeleteOfflineUser(NickName:String):void{
	trace("Deleting "+NickName);
	var sql:SQLStatement = new SQLStatement();
	sql.sqlConnection = DBConnection;
	sql.text = "DELETE FROM ActiveUsers WHERE NickName = '"+NickName +"';";
	sql.execute();
	sql.addEventListener(SQLEvent.RESULT, function():void {SelectPresence() } );
	showNotification("Signed Off", NickName + " is no longer active");
}

private function InsertPresence():void {
	var sql:SQLStatement = new SQLStatement();
	sql.sqlConnection = DBConnection;
	sql.text = "SELECT NickName FROM ActiveUsers WHERE NickName = '"+CurrentNickName +"';";
	sql.execute();
	sql.addEventListener(SQLEvent.RESULT, function():void {
		var R:SQLResult = sql.getResult();
		var D:Array = R.data;
		if(D==null) {
			CreatePresence();
		}else{
			UpdatePresenceTime();
		}
		trace("Updating Presence");
	});
}

private function CreatePresence():void {
	var sql:SQLStatement = new SQLStatement();
	sql.sqlConnection = DBConnection;
	sql.text = "INSERT INTO ActiveUsers (NickName, LastUpdate) VALUES ('"+CurrentNickName+"', '"+new Date()+"');";
	sql.execute();
	sql.addEventListener(SQLErrorEvent.ERROR, function():void {
		Alert.show("Could Not Communicate to the Server on your Lan. Please make sure the you selected the right Server", "Server Error");
	});
	if(CurrentNickName){
		showNotification("Signed In", CurrentNickName+" has just signed in.");
	}
}

private function UpdatePresenceTime():void {
	var sql:SQLStatement = new SQLStatement();
	sql.sqlConnection = DBConnection;
	sql.text = "UPDATE ActiveUsers SET LastUpdate = '"+new Date()+"' WHERE NickName = '"+ CurrentNickName + "';";
	sql.execute();
	sql.addEventListener(SQLErrorEvent.ERROR, function():void {
		Alert.show("Could Not Communicate to the Server on your Lan. Please make sure the you selected the right Server", "Server Error");
	});
}

private function SelectPresence():void {
	var sql:SQLStatement = new SQLStatement();
	sql.sqlConnection = DBConnection;
	sql.text = "SELECT * FROM ActiveUsers";
	sql.execute();
	sql.addEventListener(SQLEvent.RESULT, function():void {
		var R:SQLResult = sql.getResult();
		var D:Array = R.data;
		var OU:Array = new Array();
		if(D){
			for(var i:uint = 0;i<D.length ; i++) {
				if(CheckTimeDifference(D[i].LastUpdate) > 120 ) {
					DeleteOfflineUser(D[i].NickName);
					trace(CheckTimeDifference(D[i].LastUpdate));
				}else{
					OU.push(D[i].NickName);
				}
			}
			ActiveUsersDG.dataProvider = OU;
		}
	});
}